﻿using HslCommunication.ModBus;
using Prism.Events;
using Prism.Mvvm;
using RoboAssembleX.Application.AddBoard2;
using RoboAssembleX.Application.AddGlass;
using RoboAssembleX.Application.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RoboAssembleX.Application.AddBoard1
{
    public class AddBoard1Service
    {
        public AddBoard1Service(AddBoard1Model AddBoard1Model, IEventAggregator eventAggregator)
        {
            this.AddBoard1Model = AddBoard1Model;
            this.eventAggregator = eventAggregator;
        }

        #region ReadData
        ModbusTcpNet modbus;
        Task monitorDataTask;
        private readonly AddBoard1Model AddBoard1Model;
        private readonly IEventAggregator eventAggregator;

        public void SwitchReadData()
        {
            if (AddBoard1Model.ReadDataFlag)
            {
                AddBoard1Model.ReadDataFlag = false;
                eventAggregator.GetEvent<MessageEvent>().Publish(new MessageEventArgs("基片装配设备1断开成功!", 1));
            }
            else
            {
                modbus = new ModbusTcpNet("192.168.0.101", 502);
                modbus.AddressStartWithZero = true;
                modbus.DataFormat = HslCommunication.Core.DataFormat.CDAB;
                var r = modbus.ConnectServer();
                if (r.IsSuccess)
                {
                    monitorDataTask = new Task(ReadDataJob);
                    monitorDataTask.Start();
                    AddBoard1Model.ReadDataFlag = true;
                    eventAggregator.GetEvent<MessageEvent>().Publish(new MessageEventArgs("基片装配设备1连接成功!", 1));
                }
                else
                {
                    AddBoard1Model.ReadDataFlag = false;
                    eventAggregator.GetEvent<MessageEvent>().Publish(new MessageEventArgs("基片装配设备1连接失败!", 1));
                }
            }
        }
        void ReadDataJob()
        {
            while (AddBoard1Model.ReadDataFlag)
            {
                var result = modbus.ReadBool("91");
                if (result.IsSuccess)
                {
                    AddBoard1Model.AllowRemove = result.Content;
                    AddBoard1Model.Running = !result.Content;
                }
            }
        }

        public void Action()
        {
            if (!AddBoard1Model.Running)
            {
                var result = modbus.Write("93", true);
            }
        }
        #endregion
    }
}
